<?php
namespace Admin\Logic;

use Think\Model\RelationModel;
/**
 * 分类逻辑定义
 * Class CatsLogic
 * @package Admin\Logic
 */
class EvaluationCatLogic extends RelationModel
{
    /**
     * 改变或者添加分类时 需要修改他下面的 parent_id_path  和 level
     * @global type $cat_list 所有商品分类
     * @param type $parent_id_path 指定的id
     * @return 返回数组 Description
     */
    public function refresh_cat($id)
    {
        $GoodsCategory = M("evaluation_cat"); // 实例化User对象
        $cat = $GoodsCategory->where("cat_id = $id")->find(); // 找出他自己
        // 刚新增的分类先把它的值重置一下
        if($cat['parent_id_path'] == '')
        {
            ($cat['parent_id'] == 0) && $GoodsCategory->execute("UPDATE tp_evaluation_cat set  parent_id_path = '0_$id', level = 1 where cat_id = $id"); // 如果是一级分类
            $GoodsCategory->execute("UPDATE tp_evaluation_cat AS a ,tp_evaluation_cat AS b SET a.parent_id_path = CONCAT_WS('_',b.parent_id_path,'$id'),a.level = (b.level+1) WHERE a.parent_id=b.cat_id AND a.cat_id = $id");
            $cat = $GoodsCategory->where("cat_id = $id")->find(); // 从新找出他自己
        }

        if($cat['parent_id'] == 0) //有可能是顶级分类 他没有老爸
        {
            $parent_cat['parent_id_path'] =   '0';
            $parent_cat['level'] = 0;
        }
        else{
            $parent_cat = $GoodsCategory->where("cat_id = {$cat['parent_id']}")->find(); // 找出他老爸的parent_id_path
        }
        $replace_level = $cat['level'] - ($parent_cat['level'] + 1); // 看看他 相比原来的等级 升级了多少  ($parent_cat['level'] + 1) 他老爸等级加一 就是他现在要改的等级
        $replace_str = $parent_cat['parent_id_path'].'_'.$id;
        $GoodsCategory->execute("UPDATE `tp_evaluation_cat` SET parent_id_path = REPLACE(parent_id_path,'{$cat['parent_id_path']}','$replace_str'), level = (level - $replace_level) WHERE  parent_id_path LIKE '{$cat['parent_id_path']}%'");
    }

    /**
     * 获得指定分类下的子分类的数组
     *
     * @access  public
     * @param   int     $cat_id     分类的ID
     * @param   int     $selected   当前选中分类的ID
     * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
     * @param   int     $level      限定返回的级数。为0时返回所有级数
     * @return  mix
     */
    public function evaluation_cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0,$id)
    {

            //先看有没有,没有的话先插入
            $find=M('evaluation_cat')->where('category_id='.$id)->find();
            if($find==false){
                    //查询分类的名称是不是手机
                    $cate=M('goods_category')->where('id='.$id)->field('parent_id_path')->find();

                    $explode=explode("_",$cate['parent_id_path']);
                    $first=M('goods_category')->where('id='.$explode['1'])->field('name')->find();
                    if($first['name']=="手机"){
                        //先插入大分类
//                        $sda['cat_name']="手机";
//                        $sda['category_id']=$id;
//                        $sda_add=M('evaluation_cat')->add($sda);
//                       $first_id = M('evaluation_cat')->getLastInsID();
//                        //加入手机的二级分类
//                        $mobile_cate=array(
//                            '0'=>'1.成色',
//                            '1'=>'2.容量',
//                            '2'=>'3.功能',
//                            '3'=>'4.购买来源',
//                            '4'=>'5.是否维修过'
//                            );
//                       foreach ($mobile_cate as $key => $value) {
//                          $v['cat_name']=$value;
//                          $v['parent_id']=$first_id;
//                          $v['category_id']=$id;
//                          $two_add=M('evaluation_cat')->add($v);
//                       }
//                       //查询出二级分类
//                       $two=M('evaluation_cat')->where('parent_id='.$first_id)->field('cat_name,cat_id')->select();
//
//                       foreach ($two as $key => $vv) {
//
//                              if($vv['cat_name']=="1.成色"){
//                                    $third_cate=array(
//                                    '0'=>'九成新',
//                                    '1'=>'八成新'
//                                    );
//                             }else if($vv['cat_name']=="2.容量"){
//                                $third_cate=array(
//                                    '0'=>'120G',
//                                    '1'=>'60G'
//                                    );
//                             }else if($vv['cat_name']=="3.功能"){
//                                $third_cate=array(
//                                    '0'=>'功能完好',
//                                    '1'=>'功能损坏'
//                                    );
//                             }else if($vv['cat_name']=="4.购买来源"){
//                                $third_cate=array(
//                                    '0'=>'大陆国行',
//                                    '1'=>'香港行货'
//                                    );
//                             }else if($vv['cat_name']=="5.是否维修过"){
//                                 $third_cate=array(
//                                    '0'=>'维修一次',
//                                    '1'=>'维修二次'
//                                    );
//                             }
//                            foreach ($third_cate as $key => $v) {
//                                $thi_data=array();
//                                 $thi_data['cat_name']=$v;
//                                 $thi_data['parent_id']=$vv['cat_id'];
//                                 $thi_data['category_id']=$id;
//                                 $thi_data['level'] = 3;
//                                $thi_add=M('evaluation_cat')->add($thi_data);
//                            }
//                       }

                    }else{//其他
                             //先插入大分类
                        $sda['cat_name']="相机-镜头-摄像机";
                        $sda['category_id']=$id;
                        $sda_add=M('evaluation_cat')->add($sda);
                       $first_id = M('evaluation_cat')->getLastInsID();
                        //加入手机的二级分类
                        $mobile_cate=array(
                            '0'=>'1.购买渠道',
                            '1'=>'2.取景器与CMOS',
                            '2'=>'3.屏幕',
                            '3'=>'4.功能',
                            '4'=>'5.购买渠道'
                            );
                       foreach ($mobile_cate as $key => $value) {
                          $v['cat_name']=$value;
                          $v['parent_id']=$first_id;
                          $v['category_id']=$id;
                          $two_add=M('evaluation_cat')->add($v);
                       }
                       //查询出二级分类
                       $two=M('evaluation_cat')->where('parent_id='.$first_id)->field('cat_name,cat_id')->select();

                       foreach ($two as $key => $vv) {

                              if($vv['cat_name']=="1.购买渠道"){
                                    $third_cate=array(
                                    '0'=>'机身全套包装，包新未使用，或轻微使用痕迹',
                                    '1'=>'机身有油光、磨损、掉漆、划痕等使用痕迹',
                                    '2'=>'机身严重使用痕迹，脱胶或磕碰'
                                    );
                             }else if($vv['cat_name']=="2.取景器与CMOS"){
                                $third_cate=array(
                                    '0'=>'取景器 CMOS 通透干净无灰',
                                    '1'=>'取景器 CMOS 通透干净无霉'
                                    );
                             }else if($vv['cat_name']=="3.屏幕"){
                                $third_cate=array(
                                    '0'=>'触摸屏完好',
                                    '1'=>'细微划痕'
                                    );
                             }else if($vv['cat_name']=="4.功能"){
                                $third_cate=array(
                                    '0'=>'功能无误',
                                    '1'=>'功能缺少'
                                    );
                             }else if($vv['cat_name']=="5.购买渠道"){
                                 $third_cate=array(
                                    '0'=>'维大陆国行',
                                    '1'=>'香港行货',
                                    '2'=>'非国行港版 - 无锁版',
                                    '3'=>'非国行港版 - 有锁版'
                                    );
                             }
                            foreach ($third_cate as $key => $v) {
                                $thi_data=array();
                                 $thi_data['cat_name']=$v;
                                 $thi_data['parent_id']=$vv['cat_id'];
                                 $thi_data['category_id']=$id;
                                $thi_add=M('evaluation_cat')->add($thi_data);
                            }
                       }

                    }

            }

        static $res = NULL;

        if ($res === NULL)
        {
            $data = false;//read_static_cache('art_cat_pid_releate');
            if ($data === false)
            {
            	$cat_type = I('cat_type');
            	if($cat_type == ""){
                    // $where = " where 1=1";
            		$where = " where c.category_id=".$id;
            	}else{
            		$where = " where c.cat_type=".$cat_type;
            	}
                $sql = "SELECT c.*, COUNT(s.cat_id) AS has_children FROM __PREFIX__evaluation_cat AS c".
                    " LEFT JOIN __PREFIX__evaluation_cat AS s ON s.parent_id=c.cat_id $where ".
                    " GROUP BY c.cat_id  ORDER BY parent_id, sort_order";
                $res = M('evaluation_cat')->query($sql);
                //write_static_cache('art_cat_pid_releate', $res);
            }
            else
            {
                $res = $data;
            }
        }


        if (empty($res) == true)
        {
            return $re_type ? '' : array();
        }

        $options = $this->evaluation_cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

        /* 截取到指定的缩减级别 */
        if ($level > 0)
        {
            if ($cat_id == 0)
            {
                $end_level = $level;
            }
            else
            {
                $first_item = reset($options); // 获取第一个元素
                $end_level  = $first_item['level'] + $level;
            }

            /* 保留level小于end_level的部分 */
            foreach ($options AS $key => $val)
            {
                if ($val['level'] >= $end_level)
                {
                    unset($options[$key]);
                }
            }
        }

        $pre_key = 0;
        foreach ($options AS $key => $value)
        {
            $options[$key]['has_children'] = 1;
            if ($pre_key > 0)
            {
                if ($options[$pre_key]['cat_id'] == $options[$key]['parent_id'])
                {
                    $options[$pre_key]['has_children'] = 1;
                }
            }
            $pre_key = $key;

        }

        if ($re_type == true)
        {
            $select = '';
            foreach ($options AS $var)
            {
                $select .= '<option value="' . $var['cat_id'] . '" ';
                //$select .= ' cat_type="' . $var['cat_type'] . '" ';
                $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
                $select .= '>';
                if ($var['level'] > 0)
                {
                    $select .= str_repeat('&nbsp;', $var['level'] * 4);
                }
                $select .= htmlspecialchars(addslashes($var['cat_name'])) . '</option>';
            }

            return $select;
        }
        else
        {
            foreach ($options AS $key => $value)
            {
                ///$options[$key]['url'] = build_uri('evaluation_cat', array('acid' => $value['cat_id']), $value['cat_name']);
            }

            return $options;
        }
    }

    /**
     * 过滤和排序所有文章分类，返回一个带有缩进级别的数组
     *
     * @access  private
     * @param   int     $cat_id     上级分类ID
     * @param   array   $arr        含有所有分类的数组
     * @param   int     $level      级别
     * @return  void
     */
    public function evaluation_cat_options($spec_cat_id, $arr)
    {
        static $cat_options = array();

        if (isset($cat_options[$spec_cat_id]))
        {
            return $cat_options[$spec_cat_id];
        }

        if (!isset($cat_options[0]))
        {
            $level = $last_cat_id = 0;
            $options = $cat_id_array = $level_array = array();
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $cat_id = $value['cat_id'];
                    if ($level == 0 && $last_cat_id == 0)
                    {
                        if ($value['parent_id'] > 0)
                        {
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['parent_id'] == $last_cat_id)
                    {
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                    break;
                }
            }
            $cat_options[0] = $options;
        }
        else
        {
            $options = $cat_options[0];
        }

        if (!$spec_cat_id)
        {
            return $options;
        }
        else
        {
            if (empty($options[$spec_cat_id]))
            {
                return array();
            }

            $spec_cat_id_level = $options[$spec_cat_id]['level'];

            foreach ($options AS $key => $value)
            {
                if ($key != $spec_cat_id)
                {
                    unset($options[$key]);
                }
                else
                {
                    break;
                }
            }

            $spec_cat_id_array = array();
            foreach ($options AS $key => $value)
            {
                if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                    ($spec_cat_id_level > $value['level']))
                {
                    break;
                }
                else
                {
                    $spec_cat_id_array[$key] = $value;
                }
            }
            $cat_options[$spec_cat_id] = $spec_cat_id_array;

            return $spec_cat_id_array;
        }
    }

}
